<?php
/**
 * @title 63. 不同路径 II - 动态规划+递归
 * @author start2004
 */

class Solution {

    /**
     * @param Integer[][] $obstacleGrid
     * @return Integer
     */
    function uniquePathsWithObstacles($obstacleGrid) {
        /**
         * * 0 → → m
         * ↓
         * ↓
         * n
         *
         * @since 2020-07-23 极端情况排除
         */
        $n = count($obstacleGrid);
        if($n == 0){
            return 0;
        } else {}
        $m = count($obstacleGrid[0]);
        if($m == 0){
            return 0;
        } else {}

        /**
         * @since 2020-07-06 终点为1, 障碍物, 直接返回0
         */
        if($obstacleGrid[$n-1][$m-1] == 1){
            $result = 0;
        } else {
            /**
             * @since 2020-07-23 防止重复计算
             */
            $this->dps = [];
            $result = self::path($obstacleGrid, $n-1, $m-1);
        }

        /**
         * @return
         */
        return $result;
    }

    /**
     * @title 返回数组到`m x n`的有效路径
     * @author start2004
     * @since 2020-07-06 Created
     *
     * @param array $nums
     * @param int $n
     * @param int $m
     * @return int
     */
    function path($nums = [], $n = 0, $m = 0){
        if(isset($this->dps[$n][$m])){
            return $this->dps[$n][$m];
        } else {}

        /**
         * @since 2020-07-06 路径总和
         */
        $s = 0;

        /**
         * @since 2020-07-23 网格只有1个点
         */
        if($n == 0 AND $m == 0){
            $s = 1;
        } else {
            /**
             * @since 2020-07-06 dp(m,n) = nums[n-1][m-1] * (dp(m,n-1) + dp(m-1,n))
             */
            if($n > 0){
                $v2 = $nums[$n-1][$m];
                if($v2 == 0){
                    $s += self::path($nums, $n-1, $m);
                } else {}
            } else {}

            if($m > 0){
                $v1 = $nums[$n][$m-1];
                if($v1 == 0){
                    $s += self::path($nums, $n, $m-1);
                } else {}
            } else {}
        }

        /**
         * @return
         */
        $this->dps[$n][$m] = $s;
        return $s;
    }
}




/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.06.php
 */
$datas = [
    [
        [0,0,0],
        [0,1,0],
        [0,0,0]
    ],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->uniquePathsWithObstacles($data);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
